package your.rfgui.extgui.controller.tree;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import your.rfgui.extgui.controller.tree.data.LabelDataItem;
import your.rfgui.extgui.data.intf.DataItem;
import your.rfgui.extgui.data.intf.GuiParentChildEntity;
import your.rfgui.extgui.service.intf.GuiParentChildService;

public class ParentChildTreeController<T extends GuiParentChildEntity<T>> extends AbstractTreeController {

   private static final Logger log = Logger.getLogger(ParentChildTreeController.class);
   /** the entity service providing the entities needed for this tree */
   private GuiParentChildService<T> entityService;
   /** the top level data item, here: the label data item */
   private List<DataItem> viewRootList = new ArrayList<DataItem>();

   public ParentChildTreeController(String treeRootNodeLabel, GuiParentChildService<T> entityService) {
      this.entityService = entityService;
      /** build top level item */
      viewRootList.add(new LabelDataItem(treeRootNodeLabel));
      /** create tree view nodes */
      super.populate();
      /** expand the top level label data item */
      rootNodes.get(0).setExpanded(true);
      setSelectedViewNode(rootNodes.get(0));
   }

   /**
    * Retrieve the root data list to be displayed in the tree view
    */
   @Override
   List<? extends DataItem> getViewRootList() {
      log.info("getViewRootList");
      return viewRootList;
   }

   /**
    * Returns the children data item list for the given data item
    */
   @Override
   List<? extends DataItem> getViewChildren(DataItem dataItem) {
      log.debug("getViewChildren");

      assert (dataItem != null);
      if (dataItem instanceof LabelDataItem) {
         return entityService.getRootList();
      } else {
         assert (dataItem instanceof GuiParentChildEntity);
         @SuppressWarnings("unchecked")
         List<T> childrenList = ((GuiParentChildEntity<T>) dataItem).getChildren();
         return childrenList;
      }
   }
}
